package org.example.pet.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.pet.common.Result;
import org.example.pet.dto.UserDetailDTO;
import org.example.pet.dto.UserPageQueryDTO;
import org.example.pet.pojo.User;
import org.example.pet.service.UserService;
import org.example.pet.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        log.info("用户注册... 用户名：{}，邮箱：{}", user.getUsername(), user.getEmail());
        userService.register(user);
        return Result.success("注册成功");
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody User user) {
        log.info("用户登录... 用户名：{}", user.getUsername());
        Map<String, Object> result = userService.login(user);
        return Result.success("登录成功", result);
    }

    /**
     * 获取用户详情
     * @param request
     * @return
     */
    @GetMapping("/info")
    public Result<UserDetailDTO> getUserDetail(HttpServletRequest request) {
        // 从Token解析用户名
        String token = request.getHeader("Authorization").substring(7);
        String username = jwtUtil.getUsernameFromToken(token);

        // 查询用户全量信息
        User user = userService.getUserByUsername(username);
        UserDetailDTO dto = new UserDetailDTO();
        dto.setUserId(user.getUserId());
        dto.setUsername(user.getUsername());
        dto.setRole(user.getRole());
        dto.setPhone(user.getPhone());
        dto.setAddress(user.getAddress());
        dto.setStatus(user.getStatus());
        dto.setEmail(user.getEmail());

        return Result.success("获取用户信息成功", dto);
    }
    
    @PostMapping("/updateUserInfo")
    public Result<UserDetailDTO> updateUserInfo(@RequestBody User user) {
        log.info("修改用户信息... 用户名：{}", user.getUsername());
        UserDetailDTO userDetailDTO = userService.updateUserInfo(user);
        return Result.success("修改用户信息成功", userDetailDTO);
    }
    
    @GetMapping("/page")
    public Result<Page<User>> page(@ModelAttribute UserPageQueryDTO dto) {
        log.info("用户信息分页查询...");
        Page<User> users = userService.page(dto);
        return Result.success(users);
    }

    @PostMapping("/delete/{userId}")
    public Result<String> deleteUser(@PathVariable("userId") Long userId) {
        log.info("删除用户：{}", userId);
        userService.removeById(userId);
        return Result.success("删除成功");
    }
}